package com.aprivate.kn.ratingsystem.activity;

import android.annotation.TargetApi;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aprivate.kn.ratingsystem.R;
import com.aprivate.kn.ratingsystem.bean.LoginResponseBean;
import com.aprivate.kn.ratingsystem.bean.ResponseBean;
import com.aprivate.kn.ratingsystem.config;
import com.aprivate.kn.ratingsystem.daoBean.User;
import com.aprivate.kn.ratingsystem.daoutil.UserDaoUtil;
import com.example.okhttputils.CallBackUtil;
import com.example.okhttputils.OkhttpUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static android.Manifest.permission.READ_CONTACTS;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    private static final int REQUEST_READ_CONTACTS = 0;
    private EditText mEmailView;
    private EditText mPasswordView;
    private ProgressBar mProgressView;
    private CheckBox mAutoLoginCheckBox;

    private InputMethodManager inputMethodManager;
    private Button mEmailSignInButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        preDoLogin();
    }

    /**
     * 无网络：校验存储的用户信息
     * 有网络：进行登录操作
     */
    private void preDoLogin() {
        User user = UserDaoUtil.getInstance().getUser();
        if (null != user && user.isAutoLogin()) {
            config.USER_TOKEN_VALUE = user.getUserToken();
            jumpProjectListActivity();
        } else {
            initView();
        }

    }

    private void initView() {
        mEmailView = findViewById(R.id.email);
        mAutoLoginCheckBox = findViewById(R.id.checkbox_auto_login);
        populateAutoComplete();
        mPasswordView = findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    inputMethodManager.hideSoftInputFromWindow(mPasswordView.getWindowToken(), 0); //强制隐藏键盘
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        mEmailSignInButton = findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //隐藏键盘
                inputMethodManager.hideSoftInputFromWindow(mEmailSignInButton.getWindowToken(), 0); //强制隐藏键盘
                attemptLogin();
            }
        });
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new View.OnClickListener() {
                        @Override
                        @TargetApi(Build.VERSION_CODES.M)
                        public void onClick(View v) {
                            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                        }
                    });
        } else {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    private void attemptLogin() {
        mEmailView.setError(null);
        mPasswordView.setError(null);
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            showProgress(true);
            doLogin(email, password);
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user's 'profile' contact.
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
                // Select only email addresses.
                ContactsContract.Contacts.Data.MIMETYPE +
                        " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                .CONTENT_ITEM_TYPE},

                // Show primary email addresses first. Note that there won't be
                // a primary email address if the user hasn't specified one.
                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }

        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private interface ProfileQuery {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };
        int ADDRESS = 0;
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
    }

    private void doLogin(String email, final String password) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("name", email);
        paramsMap.put("password", password);
        OkhttpUtil.okHttpPost(config.URL + config.Login_Url, paramsMap, config.getHeaderMap(), new CallBackUtil.CallBackString() {
            @Override
            public void onResponse(String response) {
                showProgress(false);
                Gson gson = new Gson();
                ResponseBean responseBean = gson.fromJson(response, ResponseBean.class);
                if (responseBean.getStatusCode().equals("200")) {
                    LoginResponseBean loginResponseBean = gson.fromJson(responseBean.getData().toString(), LoginResponseBean.class);
                    UserDaoUtil.getInstance().deleteAll();
                    User user = new User();
                    user.setAutoLogin(mAutoLoginCheckBox.isChecked());
                    user.setUserId(loginResponseBean.getId());
                    user.setUserName(loginResponseBean.getName());
                    user.setPassWord(password);
                    user.setUserToken(loginResponseBean.getToken());
                    user.setUserType(loginResponseBean.getType());
                    UserDaoUtil.getInstance().insertUser(user);
                    config.USER_TOKEN_VALUE = loginResponseBean.getToken();
                    jumpProjectListActivity();
                } else {
                    if (responseBean.getStatusCode().equals("-1")) {
                        mPasswordView.setError((CharSequence) responseBean.getErrorInfo());
                    }
                }

            }

            @Override
            public void onFailure(Call call, Exception e) {
                showProgress(false);
            }
        });
    }

    private void jumpProjectListActivity() {
        Intent intent = new Intent(this, ProjectListActivity.class);
        this.startActivity(intent);
        finish();
    }
}

